/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package controlador;

import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.ClientsDB;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.Date;
import model.PaisosDB;
import java.util.Map;
import model.CarretDB;
import java.text.DecimalFormat;

/**
 *
 * @author sheked
 */
public class ServletUsuari extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        if (request.getSession(false) == null) {
            response.sendRedirect("controlador");
        }

        if (request.getParameter("op") == null) {
            response.sendError(3);
        }
        RequestDispatcher reqDispatcher = null;
        HttpSession sessio = request.getSession(false);
        switch(Integer.parseInt(request.getParameter("op"))) {
            case 0: //login usuari
                try {
                    ClientsDB clientsDB = new ClientsDB();
                    CarretDB carret = new CarretDB();
                    Map<String, Object> rs = clientsDB.consultaClient(request.getParameter("user"), request.getParameter("pass"));
                    if (rs != null && !rs.isEmpty()) {
                        sessio.setAttribute("nom", rs.get("nom"));
                        sessio.setAttribute("id", Integer.valueOf(((BigDecimal)rs.get("id_client")).intValue()));
                        sessio.setAttribute("cognoms", rs.get("cognoms"));
                        if (((BigDecimal)rs.get("admin")).intValue() == 1) {
                            sessio.setAttribute("isAdmin", Boolean.TRUE);
                        } else {
                            sessio.setAttribute("isAdmin", Boolean.FALSE);
                        }
                        sessio.setAttribute("isLogged", Boolean.TRUE);
                        sessio.setAttribute("numProdPagina", Integer.valueOf(((BigDecimal)rs.get("numprodpag")).intValue()));
                        if (sessio.getAttribute("idCarret") != null) {
                            if (!carret.update((Integer)sessio.getAttribute("idCarret"), ((BigDecimal)rs.get("id_client")).intValue())) {
                                noLogin(sessio);
                                response.sendError(7);
                            }
                            recarregarCarret(sessio, carret);
                        }
                    } else {
                        noLogin(sessio);
                        response.sendError(1);
                    }
                    reqDispatcher = getServletContext().getRequestDispatcher("/menuUserH.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception ex) {
                    response.sendError(1);
                }
                break;
            case 1: //logout
                noLogin(sessio);
                try {
                    CarretDB carret = new CarretDB();
                    reqDispatcher = getServletContext().getRequestDispatcher("/menuUserH.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception ex) {
                    response.sendError(4);
                }
                break;
            case 2: //mostrar per registrar-se
                try {
                    PaisosDB paisosDB = new PaisosDB();
                    request.setAttribute("paisos", paisosDB.consultaPaisos());
                    reqDispatcher = getServletContext().getRequestDispatcher("/registrar.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception ex) {
                    response.sendError(4);
                }
                break;
            case 3: //registrar-se
                try {
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    String pass = request.getParameter("password");
                    String pass2 = request.getParameter("password2");
                    if (pass.equals(pass2)) {
                        String nom = request.getParameter("nom");
                        String cognoms = request.getParameter("cognoms");
                        String dia = request.getParameter("dia");
                        String mes = request.getParameter("mes");
                        String any = request.getParameter("any");
                        Date datanaix = Date.valueOf(any + "-" + mes + "-" + dia);
                        String adreca = request.getParameter("adreca");
                        int cp = Integer.parseInt(request.getParameter("cp"));
                        String poblacio = request.getParameter("poblacio");
                        int pais = Integer.parseInt(request.getParameter("pais"));
                        String telefon = request.getParameter("telefon");
                        String email = request.getParameter("email");
                        int banc = Integer.parseInt(request.getParameter("banc"));
                        int ofi = Integer.parseInt(request.getParameter("oficina"));
                        int dc = Integer.parseInt(request.getParameter("dc"));
                        long cc = Long.parseLong(request.getParameter("cc"));

                        ClientsDB clientsDB = new ClientsDB();
                        boolean fet = clientsDB.introdueixClient(nom, cognoms, pass, datanaix, adreca, cp, poblacio, pais, telefon, email, banc, ofi, dc, cc);
                        if (fet) {
                            out.println("L'usuari " + nom + " s'ha registrat satisfactoriament");
                        } else {
                            out.println("Hi ha hagut algun problema a l'hora d'introduir el nou usuari " + nom);
                        }
                    } else {
                        out.println("Els passwords no concorden");
                    }
                } catch (SQLException e) {
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.println("El correu electronic especificat ja existeix");
                } catch (Exception e) {
                    response.sendError(5);
                }
                break;
            case 4: //introduir producte al carret de la compra
                try {
                    CarretDB carret = new CarretDB();
                    if (sessio.getAttribute("idCarret") == null) {
                       if (sessio.getAttribute("id") != null) {
                           sessio.setAttribute("idCarret", Integer.valueOf(carret.crear((Integer)sessio.getAttribute("id"))));
                       } else {
                           sessio.setAttribute("idCarret", Integer.valueOf(carret.crear()));
                       }
                    }
                    if ((Integer)sessio.getAttribute("idCarret") >=0) {
                        int res = carret.introduir((Integer)sessio.getAttribute("idCarret"),Integer.parseInt(request.getParameter("id")), Integer.parseInt(request.getParameter("num")));
                        if (res == 0) {
                            if (recarregarCarret(sessio,carret)) {
                                reqDispatcher = getServletContext().getRequestDispatcher("/menuUserH.jsp");
                                reqDispatcher.forward(request,response);
                            } else {
                                response.sendError(4);
                            }
                        } else if (res > 2) {
                            response.sendError(8);
                        } else if (res == 1) {
                            response.sendError(9);
                        }
                    } else {
                       sessio.setAttribute("idCarret", null);
                       response.sendError(6);
                    }
                } catch (Exception e) {
                    response.sendError(6);
                }
                break;
            case 5: //Borrar producte del carret de la compra
                try {
                    CarretDB carret = new CarretDB();
                    if (!carret.eliminarItem((Integer)sessio.getAttribute("idCarret"), Integer.parseInt(request.getParameter("id")))) {
                        response.sendError(10);
                    }
                    if (recarregarCarret(sessio,carret)) {;
                        reqDispatcher = getServletContext().getRequestDispatcher("/menuUserH.jsp");
                        reqDispatcher.forward(request,response);
                    } else {
                        response.sendError(4);
                    }
                    reqDispatcher = getServletContext().getRequestDispatcher("/menuUserH.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception e) {
                    response.sendError(10);
                }
                break;
            case 6: //Borrar tots els productes del carret de la compra
                try {
                    CarretDB carret = new CarretDB();
                    if (!carret.buidar((Integer)sessio.getAttribute("idCarret"))) {
                        response.sendError(10);
                    }
                    if (recarregarCarret(sessio,carret)) {
                        reqDispatcher = getServletContext().getRequestDispatcher("/menuUserH.jsp");
                        reqDispatcher.forward(request,response);
                    } else {
                        response.sendError(4);
                    }
                    reqDispatcher = getServletContext().getRequestDispatcher("/menuUserH.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception e) {
                    response.sendError(11);
                }
                break;
            case 7: //Confirmar la compra dels productes del carret
                try {
                    CarretDB carret = new CarretDB();
                    int estat = carret.pagar((Integer)sessio.getAttribute("idCarret"));
                    if (estat != 0) {
                        response.sendError(12);
                    }
                    sessio.setAttribute("idCarret", null);
                    sessio.setAttribute("totalCarret", Float.valueOf((float)0.0));
                    sessio.setAttribute("itemsCarret", Integer.valueOf(0));
                    reqDispatcher = getServletContext().getRequestDispatcher("/menuUserH.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception e) {
                   response.sendError(12);
                }
                break;
            case 8: //Mirar Preferencies
                try {
                    CarretDB carret = new CarretDB();
                    request.setAttribute("carrets", carret.carretsAnteriors((Integer) sessio.getAttribute("id")));
                    request.setAttribute("llistatCarret", sessio.getAttribute("llistatCarret"));
                    request.setAttribute("totalCarret", sessio.getAttribute("totalCarret"));
                    reqDispatcher = getServletContext().getRequestDispatcher("/preferencies.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception e) {

                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.println("<pre>");
                    e.printStackTrace(out);
                    out.println("</pre>");
                   //response.sendError(20);
                }
                break;
            case 9: //Mirar carret a preferencies
                try {
                    CarretDB carret = new CarretDB();
                    DecimalFormat formatter = new DecimalFormat("#####0.00");
                    float pt = carret.preuTotal(Integer.parseInt(request.getParameter("id")));
                    int items = carret.itemsTotal(Integer.parseInt(request.getParameter("id")));
                    if (pt >= 0 && items >= 0) {
                        request.setAttribute("totalCarret", formatter.format(pt));
                        request.setAttribute("llistatCarret", carret.llistat(Integer.parseInt(request.getParameter("id"))));
                    }
                    reqDispatcher = getServletContext().getRequestDispatcher("/detallsPref.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception e) {

                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.println("<pre>");
                    e.printStackTrace(out);
                    out.println("</pre>");
                   //response.sendError(21);
                }
                break;
            case 10: //activar carret anterior
                try {
                    CarretDB carret = new CarretDB();
                    sessio.setAttribute("idCarret", Integer.parseInt(request.getParameter("id")));
                    recarregarCarret(sessio, carret);
                    request.setAttribute("carrets", carret.carretsAnteriors((Integer) sessio.getAttribute("id")));
                    request.setAttribute("llistatCarret", sessio.getAttribute("llistatCarret"));
                    request.setAttribute("totalCarret", sessio.getAttribute("totalCarret"));
                    reqDispatcher = getServletContext().getRequestDispatcher("/preferencies.jsp");
                    reqDispatcher.forward(request,response);
                } catch (Exception e) {
                    response.setContentType("text/html;charset=UTF-8");
                    PrintWriter out = response.getWriter();
                    out.println("<pre>");
                    e.printStackTrace(out);
                    out.println("</pre>");
                   //response.sendError(22);
                }
                break;
            case 11: //carregar el menu de usuari
                reqDispatcher = getServletContext().getRequestDispatcher("/menuUserH.jsp");
                reqDispatcher.forward(request,response);
                break;
            default:
                response.sendError(2);
                break;
        }

    }

    private void noLogin(HttpSession sessio) {
        sessio.setAttribute("id", null);
        sessio.setAttribute("nom", null);
        sessio.setAttribute("cognoms", null);
        sessio.setAttribute("isAdmin", Boolean.FALSE);
        sessio.setAttribute("isLogged", Boolean.FALSE);
        sessio.setAttribute("numProdPagina",Integer.valueOf(9));
    }

    private boolean recarregarCarret(HttpSession sessio, CarretDB carret) throws SQLException {
        if(sessio.getAttribute("idCarret") != null) {
            DecimalFormat formatter = new DecimalFormat("#####0.00");
            float pt = carret.preuTotal((Integer)sessio.getAttribute("idCarret"));
            int items = carret.itemsTotal((Integer)sessio.getAttribute("idCarret"));
            if (pt >= 0 && items >= 0) {
                sessio.setAttribute("totalCarret", formatter.format(pt));
                sessio.setAttribute("itemsCarret", items);
                sessio.setAttribute("llistatCarret", carret.llistat((Integer)sessio.getAttribute("idCarret")));
                return true;
            } else {
                return false;
            }
        }
        return false;

    }


    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
